//
//  ZKLineChartView.m
//  Private_Object
//
//  Created by pro on 16/10/6.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "ZKLineChartView.h"

// view
#import "ZKLineChartBgView.h"       // 背景
#import "ZKLineChartPopView.h"      // 按钮点击弹出视图

@interface ZKLineChartView () <UIScrollViewDelegate>
{
    NSInteger _lines;                       // 行数
    CGFloat   _axisOfYMax;                  // y轴最大坐标

    NSInteger _selectedBtnIndex;            // 当前选中的按钮索引
}


// data
@property (nonatomic, strong) NSMutableArray *axisOfYArray;     // y轴坐标
@property (nonatomic, strong) NSMutableArray *axisOfXArray;     // x轴坐标

@property (nonatomic, strong) NSArray *dataArray; // 每个点对应的按钮数组
@property (nonatomic, strong) NSMutableArray *pointButtonsArray; // 每个点对应的按钮数组
@property (nonatomic, strong) NSMutableArray *pointsArray;       // 每个点的数组

// view
@property (nonatomic, strong) UIScrollView *axisOfYView;         // y轴视图
@property (nonatomic, strong) UIScrollView *axisOfXView;         // x轴视图
@property (nonatomic, strong) UIScrollView *chartScrollView;     // 表格滑动视图
@property (nonatomic, strong) ZKLineChartBgView *bgview;         // 背景
@property (nonatomic, strong) ZKLineChartPopView *popview;       // 弹出视图


@end

@implementation ZKLineChartView

static CGFloat      kColWidth   = 50;           // 一列的宽度

#pragma mark - getter
// 滑动视图
- (UIScrollView *)chartScrollView {
    if (!_chartScrollView) {
        _chartScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(self.axisOfYView.width, 0, self.width - self.axisOfYView.width, self.axisOfYView.height)];
        _chartScrollView.backgroundColor = [UIColor clearColor];
        _chartScrollView.bounces = NO;
        _chartScrollView.showsHorizontalScrollIndicator = NO;
        _chartScrollView.showsVerticalScrollIndicator = NO;
        _chartScrollView.delegate = self;
    }
    
    return _chartScrollView;
}
- (ZKLineChartBgView *)bgview {
    if (!_bgview) {
        _bgview = [[ZKLineChartBgView alloc] initWithFrame:self.chartScrollView.bounds];
        [self.chartScrollView addSubview:_bgview];
        [_chartScrollView addSubview:_bgview];
    }
    return _bgview;
}
// y轴坐标视图
- (UIScrollView *)axisOfYView {
    if (!_axisOfYView) {
        _axisOfYView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 0, self.height - 40)];
        _axisOfYView.backgroundColor = [UIColor clearColor];
    }
    return _axisOfYView;
}
// x轴坐标视图
- (UIScrollView *)axisOfXView {
    if (!_axisOfXView) {
        _axisOfXView = [[UIScrollView alloc] initWithFrame:CGRectMake(self.chartScrollView.left, self.chartScrollView.bottom, self.chartScrollView.width, 40)];
        _axisOfXView.backgroundColor = [UIColor clearColor];
        _axisOfXView.bounces = NO;
        _axisOfXView.showsHorizontalScrollIndicator = NO;
        _axisOfXView.showsVerticalScrollIndicator = NO;
        _axisOfXView.delegate = self;

    }
    return _axisOfXView;
}



#pragma mark - init
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
        _selectedBtnIndex       = -1;                       // -1表示没选中
        self.pointsArray        = [NSMutableArray array];
        self.pointButtonsArray  = [NSMutableArray array];
        self.axisOfXArray       = [NSMutableArray array];
        self.axisOfYArray       = [NSMutableArray array];

        
        [self addSubview:self.axisOfYView];                 // y轴坐标图
        [self addSubview:self.chartScrollView];             // 折线图
        [self addSubview:self.axisOfXView];                 // x轴坐标图
    }
    
    return self;
}


    
#pragma mark - scroll delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (scrollView == self.chartScrollView) {
        self.axisOfXView.contentOffset = self.chartScrollView.contentOffset;
    } else {
        self.chartScrollView.contentOffset = self.axisOfXView.contentOffset;
    }
}

#pragma mark - 点击
- (void)buttonTap:(UIButton *)button {
    
    if (button.tag == _selectedBtnIndex) {
        return;
    }
    
    // 按钮的状态设置
    if (_selectedBtnIndex == -1) {
        // 第一次选择
    } else {
        UIButton *prevSelectedButton = [self.chartScrollView viewWithTag:_selectedBtnIndex];
        prevSelectedButton.selected = NO;
    }
    
    button.selected = YES;
    _selectedBtnIndex = button.tag;
    
    
    // 如果按钮的中心在上方，则弹出视图在下方显示
    // 如果按钮的中心在左侧，则弹出视图的箭头在左侧
    if (_popview) {
        [_popview removeFromSuperview];
        _popview = nil;
    }
    
    CGFloat ratio = 0.8;
    if (button.center.y < self.chartScrollView.height / 2) {
        if (button.center.x < self.chartScrollView.contentSize.width / 2) {
            ratio = -0.2;
        } else {
            ratio = -0.8;
        }
    } else {
        if (button.center.x < self.chartScrollView.contentSize.width / 2) {
            ratio = 0.2;
        } else {
            ratio = 0.8;
        }
    }
    // 点击显示视图
    _popview = [[ZKLineChartPopView alloc] initWithFrame:CGRectMake(0, 0, 120, 50) arrowPositionRatio:ratio];
    [self.chartScrollView addSubview:_popview];
    _popview.arrowPosition = button.center;
    _popview.content = [NSString stringWithFormat:@"%@套", _dataArray[button.tag - 1]];
}


#pragma mark - 外部调用
- (void)show:(BOOL)animationed {
    
    NSAssert(self.dataArray, @"请先设置数据数组");
    // 添加数据点和按钮
    [self addPointWith:self.chartScrollView dataArrar:_dataArray];
    [self addPath:animationed];
    
}
- (void)setDataArray:(NSArray *)dataArray lines:(NSInteger)lines {
    self.dataArray = dataArray;
    _lines = lines;
    // 找到最大值
    for (int i = 0; i < self.dataArray.count; i ++) {
        CGFloat numY = [self.dataArray[i] floatValue];
        if (numY > _axisOfYMax) {
            _axisOfYMax = numY;
        }
    }
    if (_axisOfYMax == 0) {
        _axisOfYMax = 1;
    } else {
        _axisOfYMax *= 1.2;
    }
    
    self.chartScrollView.contentSize = CGSizeMake(self.dataArray.count * kColWidth, 0);
    self.bgview.width = self.chartScrollView.contentSize.width;
    self.bgview.lines = @(lines);
    self.axisOfXView.contentSize = CGSizeMake(self.dataArray.count * kColWidth, 0);

    // 添加y轴坐标（暂时不要）
//    [self addAxisOfYData];
}
- (void)setAxisOfXDataArray:(NSArray *)axisOfXDataArray {
    
    NSAssert(axisOfXDataArray.count == self.dataArray.count, @"数据数组和坐标数组个数不对应，请检查");

    // x轴坐标数组添加数据
    [self.axisOfXArray addObjectsFromArray:axisOfXDataArray];
    [self addAxisOfXData];
}
// 添加x轴坐标数据
- (void)addAxisOfXData {
    
    CGFloat x, y, width, height;
    for (int i = 0; i < self.axisOfXArray.count; i ++) {
        x = i * kColWidth;
        y = 0;
        width = kColWidth;
        height = self.axisOfXView.height;
        UILabel *xLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
        xLabel.adjustsFontSizeToFitWidth = YES;
        xLabel.font = FONT(12);
        xLabel.text = self.axisOfXArray[i];
        xLabel.textColor = rgba(54, 149, 239, 1);
        xLabel.textAlignment = NSTextAlignmentCenter;
        [self.axisOfXView addSubview:xLabel];
    }
}

// 添加y轴坐标数据
- (void)addAxisOfYData {
    
    CGFloat axisOfY = 0;
    CGFloat margin = _axisOfYMax / _lines;
    axisOfY += margin;
    while (axisOfY < _axisOfYMax) {
        [self.axisOfYArray addObject:@(axisOfY)];
        axisOfY += margin;
    }
    
    // 绘制 y轴的坐标
    CGFloat x, y, width, height;
    for (int i = 0; i < self.axisOfYArray.count; i ++) {
        x = 0;
        y = 0;
        width = self.axisOfYView.width;
        height = 20;
        UILabel *yLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
        yLabel.adjustsFontSizeToFitWidth = YES;
        yLabel.font = FONT(12);
        yLabel.text = [NSString stringWithFormat:@"%@", self.axisOfYArray[i]];
        yLabel.textColor = rgba(54, 149, 239, 1);
        yLabel.textAlignment = NSTextAlignmentCenter;
        [self.axisOfYView addSubview:yLabel];
        
        yLabel.y = (1 - (CGFloat)(i+1)/_lines) * self.axisOfYView.height;
    }
}

// 添加数据点
- (void)addPointWith:(UIView *)view dataArrar:(NSArray *)dataArray {
    
    CGFloat x, y, width, height;
    for (int i = 0; i< dataArray.count; i++) {
        x = 0;
        y = 0;
        width = 40;
        height = 40;
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)];
        button.backgroundColor = [UIColor clearColor];
        button.tag = i + 1;
        
        [button setImageEdgeInsets:UIEdgeInsetsMake(12, 12, 12, 12)];
        
        [button setImage:[UIImage imageNamed:@"point_normal"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"point_selected"] forState:UIControlStateSelected];
        
        [button addTarget:self action:@selector(buttonTap:) forControlEvents:UIControlEventTouchUpInside];
        
        button.x = kColWidth / 2 + i * kColWidth;
        button.y = self.chartScrollView.height * (1 - [dataArray[i] floatValue] / _axisOfYMax);

        
        [self.pointButtonsArray addObject:button];
        NSValue *point = [NSValue valueWithCGPoint:button.center];
        [self.pointsArray addObject:point];
    }
}
// 添加path
- (void)addPath:(BOOL)animationed {
    
    // 用左下角的点作为起始点
    CGPoint firstPoint = CGPointMake(0, self.chartScrollView.height);
    // 用最右下角的点作为结束点
    CGPoint lastPoint = CGPointMake(self.chartScrollView.contentSize.width, self.chartScrollView.height);
    // 连线的path
    UIBezierPath *connectBeizer = [UIBezierPath bezierPath];
    connectBeizer.lineCapStyle = kCGLineCapRound;
    connectBeizer.lineJoinStyle = kCGLineJoinRound;
    [connectBeizer moveToPoint:firstPoint];
    
    // mask的path
    UIBezierPath *maskBezier = [UIBezierPath bezierPath];
    maskBezier.lineCapStyle = kCGLineCapRound;
    maskBezier.lineJoinStyle = kCGLineJoinMiter;
    [maskBezier moveToPoint:firstPoint];
    [maskBezier addLineToPoint:firstPoint];
    
    // 添加线条
    for (int i = 0; i < self.pointsArray.count; i++ ) {
        
        CGPoint point = [[self.pointsArray objectAtIndex:i] CGPointValue];
        [connectBeizer addLineToPoint:point];
        [maskBezier addLineToPoint:point];
    }
    
    // 画完连接path 和 maskPath
    [connectBeizer addLineToPoint:lastPoint];
    [maskBezier addLineToPoint:lastPoint];
    [maskBezier addLineToPoint:firstPoint];
    
    // 遮罩层
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.path = maskBezier.CGPath;
    // 渐变图层
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = CGRectMake(0, 0, 0, self.chartScrollView.height);
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(0, 1);
    gradientLayer.cornerRadius = 5;
    gradientLayer.masksToBounds = YES;
    gradientLayer.colors = @[(__bridge id)[UIColor colorWithRed:166/255.0 green:206/255.0 blue:247/255.0 alpha:0.7].CGColor,(__bridge id)[UIColor colorWithRed:237/255.0 green:246/255.0 blue:253/255.0 alpha:0.5].CGColor];
    gradientLayer.locations = @[@(0.5f)];
    
    CALayer *baseLayer = [CALayer layer];
    [baseLayer addSublayer:gradientLayer];
    baseLayer.mask = maskLayer;
    
    [self.chartScrollView.layer addSublayer:baseLayer];
    
    // 连接线条路径
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = connectBeizer.CGPath;
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.strokeColor = [UIColor colorWithRed:0 green:120/255.0 blue:233/255.0 alpha:1].CGColor;
    shapeLayer.lineWidth = 2;
    [self.chartScrollView.layer addSublayer:shapeLayer];
    
    // 在上述layer添加后，再添加button，这样button不会被线条挡住
    for (UIButton *button in self.pointButtonsArray) {
        [self.chartScrollView addSubview:button];
    }
    
    if (animationed) {
        // 渐变图形的动画
        CABasicAnimation *boundsAnimation = [CABasicAnimation animation];
        boundsAnimation.keyPath = @"bounds";
        boundsAnimation.duration = 3;
        boundsAnimation.toValue = [NSValue valueWithCGRect:CGRectMake(0, 0, lastPoint.x * 2, self.chartScrollView.height)];
        boundsAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        boundsAnimation.fillMode = kCAFillModeForwards;
        boundsAnimation.autoreverses = NO;
        boundsAnimation.removedOnCompletion = NO;
        [gradientLayer addAnimation:boundsAnimation forKey:@"bounds"];
        
        // 连接线条的动画
        CABasicAnimation *strokeAnimation = [CABasicAnimation animation];
        strokeAnimation.keyPath = @"strokeEnd";
        strokeAnimation.fromValue = [NSNumber numberWithFloat:0];
        strokeAnimation.toValue = [NSNumber numberWithFloat:1.0f];
        strokeAnimation.duration = 3;
        strokeAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        strokeAnimation.autoreverses = NO;
        
        [shapeLayer addAnimation:strokeAnimation forKey:@"stroke"];
    } else {
        gradientLayer.frame = CGRectMake(0, 0, lastPoint.x * 2, self.chartScrollView.height);
    }
    
    
}



@end
